package com.riant.day05;

import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname Demo1
 * @Description TODO
 * @Date 2021/3/13 22:40
 * @Created by 张斌
 */
public class Demo1 {

    private static String DB_URL="jdbc:mysql://127.0.0.1:3306/test?user=test&password=test";
    private static String sql="select * from `pet`";
    private static String DRIVERCLASS1="com.mysql.cj.jdbc.Driver";
    private static String DRIVERCLASS2="com.mysql.jdbc.Driver";
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName(DRIVERCLASS1);
        Connection connection=null;
        try {
            connection=DriverManager.getConnection(DB_URL);
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet resultSet=statement.executeQuery();
            List<Pet> list=new ArrayList<>();
            while(resultSet.next()){
//                Pet pet=new Pet();
//                DButil.toObject(resultSet,pet);
                Pet pet= (Pet) getEachRow(resultSet,Pet.class);
                list.add(pet);
            }
            for (Pet pet : list){
                Blob desp=pet.getDesp();
                byte[] bytes= desp.getBytes(1,(int) desp.length());
                System.out.println(new String(bytes,"UTF-8"));
            }
           // System.out.println(Arrays.toString(list.toArray()));
        }catch (Exception e){
            e.printStackTrace();
        }
        connection.close();
    }
    private static <T> Object getEachRow(ResultSet rs, Class<T> cls) throws Exception {
        //创建对象
        T obj = cls.getConstructor().newInstance();
        //获取结果集元数据(获取此 ResultSet 对象的列的编号、类型和属性。)
        ResultSetMetaData rd = rs.getMetaData();
        //拿到cls中的方法
        Method[] methods = cls.getDeclaredMethods();
        for (int i = 1; i <= rd.getColumnCount(); i++) {
            //获取列名
            String columnName = rd.getColumnLabel(i);
            if(columnName.equals("desp")){
                System.out.println("当前类型为Blob");
            }
            //组合方法名,set+首字母大写+后续小写
            String methodName = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);
            //遍历method查找符合项并赋值
            for (Method method : methods) {

                if (method.getName().equals(methodName)) {
                    if(method.getName().equals("setDesp")){
                        System.out.println("Blob设置");
                        method.invoke(obj, rs.getBlob(columnName));
                    }else{
                        method.invoke(obj, rs.getObject(columnName));
                    }

                }
            }
        }
        return obj;
    }
}
